#!/bin/bash
echo "===== 开始磁盘性能测试 ====="
# 记录开始时间
start_time=$(date +%s.%N)
# 检查是否为root用户运行
if [ "$USER" != "root" ]; then
    echo "脚本必须以root用户运行"
    exit 1
fi
# 收集磁盘状态信息
echo "===== 磁盘状态信息 ====="
iostat -d -k 2 5 > disk_status.log
blktrace -d sda -o blktrace_output.log -t raw &> /dev/null
hdparm -I /dev/sda > hdparm_info.log
# 运行磁盘压力测试
echo "===== 开始磁盘压力测试 ====="
fio --filename=/dev/sda1 --direct=0 --rw=readwrite --bs=4k --size=1G --numjobs=4 --runtime=60s --group_reporting > fio_test.log
# 分析结果并进行调优
echo "===== 调整磁盘参数 ====="
if [ $(grep -o "%util:" disk_status.log | tail -n 1 | awk '{print $3}' | cut -d'%' -f1) -ge "80" ]; then
    echo "调整队列深度为64"
    echo "echo 64 > /sys/block/sda/queue/nr_requests"
    echo 64 > /sys/block/sda/queue/nr_requests
fi
if [ $(grep -o "%iowait:" disk_status.log | tail -n 1 | awk '{print $3}' | cut -d'%' -f1) -ge "20" ]; then
    echo "优化电梯算法为deadline"
    echo "echo deadline > /sys/block/sda/queue/scheduler"
    echo deadline > /sys/block/sda/queue/scheduler
fi
# 收集调优后的指标
iostat_output=$(iostat -d -k | awk '/sda/' | tail -n 1)
blktrace_output=$(blktrace -r blktrace_output.log -t raw | grep -c 'READ|WRITE')
hdparm_output=$(hdparm -T /dev/sda | grep timing)
# 记录结束时间
end_time=$(date +%s.%N)
duration=$(echo "$end_time - $start_time" | bc)
echo "===== 测试摘要 ====="
echo "总执行时间: ${duration}秒"
echo "磁盘I/O读取速度: $(echo $iostat_output | awk '{print $3}')KB/s"
echo "磁盘I/O写入速度: $(echo $iostat_output | awk '{print $4}')KB/s"
echo "磁盘等待时间: $(echo $iostat_output | awk '{print $6}')ms"
echo "磁盘队列深度: $(cat /sys/block/sda/queue/nr_requests)"
# 结构化输出
echo "===== 性能指标 ====="
echo '{
    "total_time": "'$duration'",
    "disk_read_speed": "'$(echo $iostat_output | awk '{print $3}')'",
    "disk_write_speed": "'$(echo $iostat_output | awk '{print $4}')'",
    "disk_wait_time": "'$(echo $iostat_output | awk '{print $6}')'",
    "queue_depth": "'$(cat /sys/block/sda/queue/nr_requests)'"
}'